package com.xxgc.wujiaoredis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.xxgc.wujiaoredis.entity.GoodsEntity;
import com.xxgc.wujiaoredis.entity.GoodsEntityMapper;
import com.xxgc.wujiaoredis.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsEntityMapper goodsEntityMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<GoodsEntity> selectGoodsByMerchantId(String merchantId) {
        //优先从缓存里面找
        String key = "merchantId:"+merchantId;
        //如果缓存里面有就缓存里面拿
        String value = (String) redisTemplate.opsForValue().get(key);
        //Gson吧对象转成json再存储
        Gson gson = new Gson();
        if(value != null){//缓存里面有这个值
            List<GoodsEntity> list = gson.fromJson(value, List.class);
            log.info("走的缓存");
            return list;
        }else{//如果没有就查询后赋值再返回
            QueryWrapper<GoodsEntity> qw = new QueryWrapper<>();
            qw.eq("merchant_id",merchantId);
            log.info("走的数据库");
            List<GoodsEntity> goodsEntities = goodsEntityMapper.selectList(qw);

            String goodsListJson = gson.toJson(goodsEntities);
            redisTemplate.opsForValue().set(key,goodsListJson);
            return goodsEntities;
        }
    }
}
